package com.cn.sys.main.aop;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.AfterThrowing;  
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cn.sys.common.Constants;
import com.cn.sys.main.entity.SysOpeLog;
import com.cn.sys.main.entity.SysUser;
import com.cn.sys.main.service.SysOpeLogService;

@Component
@Aspect
public class ExceptionLoggerAop {

	private static Logger logger = LoggerFactory.getLogger(ExceptionLoggerAop.class);
			
	@Autowired
	private SysOpeLogService sysOpeLogService;
	
	@AfterThrowing(pointcut = "execution(* com.cn..web.*.*(..))", throwing = "ex")
    public void loggerException(Exception ex) {
		logger.info("异常类:"+ex.getClass().getSimpleName());
		logger.info("异常信息:"+ex.getMessage());
		
		SysOpeLog opeLog = new SysOpeLog();
        opeLog.setOperateType("exception");
        opeLog.setOperateUser(getOperateUser());
        String context = ex.getMessage();
        if(context!=null&&context.length()>4000){
        	context.substring(0, 3999);
        }
        opeLog.setContent(context);
        opeLog.setOperateTime(new Date());
        opeLog.setOperateObj(ex.getClass().getSimpleName());
        try {
			sysOpeLogService.save(opeLog);
		} catch (Exception e) {
			//e.printStackTrace();
			logger.info("保存异常的操作日志出错:"+e.getMessage());
		}
    }
	
	private String getOperateUser(){
    	String userName = "";
    	HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	    if(request!=null){
	    	SysUser user = (SysUser) request.getSession().getAttribute(Constants.USER_CONTEXT);
	    	if(user!=null){
	    		userName = user.getUserName();
	    	}
	    }
	    return userName;
    }
}
